const Jimp = require("jimp");
const fs = require("fs");
const path = require("path");

(async function main() {
  const folderPath = "F:/Projects/我的工具库/图片整合/交易回顾";
  const picMerge = (imgPaths) => {
    const folderPath = path.dirname(imgPaths?.[0] ?? "");
    const pngs = imgPaths.filter((item) => item.match("CB.png"));
    console.log("pngs", pngs);
    pngs.map((item) => {
      console.log("文件名称", item.split("\\"));
      const array = item.split("\\");
      const folderName = `${array[array.length - 2]}`;
      const name = array[array.length - 1];
      fs.mkdirSync(
        `F:/Projects/我的工具库/图片整合/一键提取/${array[array.length - 3]}/${
          array[array.length - 2]
        }`,
        { recursive: true }
      );
      fs.copyFile(
        item,
        `F:/Projects/我的工具库/图片整合/一键提取/${array[array.length - 3]}/${
          array[array.length - 2]
        }/${name}`,
        (err) => {
          if (err) {
            console.error("复制文件时出错:", err);
          } else {
            console.log("文件已成功复制到:");
          }
        }
      );
    });
    //   const image2 = await Jimp.read("3.png");
    // 假设两张图片大小相同，你可以直接合并
    // 如果大小不同，你可能需要调整它们的大小以匹配
  };
  const toFolder = async (folderPath) => {
    const files = await fs.readdirSync(folderPath);
    const imgFormat = [".jpg", ".jpeg", ".png", ".svg"];
    const imgPaths = [];
    for (let file of files) {
      const filePath = path.join(folderPath, file);
      if (fs.statSync(filePath).isDirectory()) {
        // 进入目录，再次读取
        toFolder(filePath);
      } else {
        const extname = path.extname(file);
        if (imgFormat.includes(extname)) {
          imgPaths.push(filePath);
        }
      }
    }
    if (imgPaths.length) {
      picMerge(imgPaths);
    }
  };
  await toFolder(folderPath);
})();
